package com.mmp.main.servlet.report;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.entity.HospitalDevice;
import com.mmp.main.util.Default;
import com.mmp.main.util.Enums;
import com.mmp.main.util.WebUtil;

public class ViewDevicesByWarrantyExpire extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		int siteId = getSessionSiteId(request);
		int locationId = getSessionLocationId(request);
		Date from = WebUtil.getParamValueAsDate(request, "pFrom", null);
		Date to = WebUtil.getParamValueAsDate(request, "pTo", null);

		Map<Integer, Object> map = new HashMap<Integer, Object>();

		String jpql = "SELECT h FROM HospitalDevice h WHERE h.site.id = ? AND h.status NOT IN (?,?)  AND h.warrantyExpireDate >= ?";
		map.put(1, siteId);
		map.put(2, Enums.DEVICE_STATUS.SCRAPPED.getStatus());
		map.put(3, Enums.DEVICE_STATUS.TRANSFERRED.getStatus());
		map.put(4, from);

		int i = 5;
		if (locationId != 0) {
			jpql += " AND h.hospital.id = ?";
			map.put(i++, locationId);
		}

		if (to != null) {
			jpql += " AND h.warrantyExpireDate <=?";
			map.put(i++, to);
		}

		jpql += " ORDER BY h.hospital.id, h.hospitalDepartment.name, h.warrantyExpireDate";

		List<HospitalDevice> deviceList = dbQueryManager.queryJPQL(jpql, map, HospitalDevice.class);
		if (deviceList == null || deviceList.isEmpty()) {
			announceErorrMessage(request, response, "لا يوجد أجهزة سينتهي ضمانها خلال الفترة التي تم تحديدها");
			return;
		}

		HashMap params = new HashMap();
		params.put(Default.REPORT_TITLE_PARAM_NAME, Enums.REPORT_TITLE.DEVICE_BY_WARRANTY_EXPIRE.getReportTitle());
		params.put("deviceList", deviceList);
		viewPDFReport("rt6.jasper", null, params, request, response);

	}
}
